package com.ctakit.proxy.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.Map;

import com.ctakit.proxy.DynamicSubject;
import com.ctakit.proxy.RealSubject;
import com.ctakit.proxy.Subject;
import com.ctakit.proxy.cglib.CglibProxy;

public class ProxyPerfTester {

	public static void main(String[] args) {

		// 创建测试对象；
		Subject nativeSubject = new RealSubject();

		RealSubject rs = new RealSubject(); // 在这里指定被代理类
		InvocationHandler ds = new DynamicSubject(rs); // 初始化代理类
		Subject dynamicProxySubject = (Subject) Proxy.newProxyInstance(rs.getClass().getClassLoader(), rs.getClass().getInterfaces(), ds);


		Subject cglibProxySubject = (Subject) new CglibProxy().getInstance(new RealSubject());


		// 执行测试；
		Map<String, Subject> tests = new LinkedHashMap<String, Subject>();
		tests.put("Native   ", nativeSubject);
		tests.put("Dynamic  ", dynamicProxySubject);
		tests.put("Cglib    ", cglibProxySubject);
		int repeatCount = 3;
		int runCount = 1000000;
		runTest(repeatCount, runCount, tests);
		runCount = 50000000;
		runTest(repeatCount, runCount, tests);
	}

	private static void runTest(int repeatCount, int runCount, Map<String, Subject> tests) {
		System.out.println(String.format(
				"\n==================== run test : [repeatCount=%s] [runCount=%s] [java.version=%s] ====================",
				repeatCount, runCount, System.getProperty("java.version")));
		for (int i = 0; i < repeatCount; i++) {
			System.out.println(String.format("\n--------- test : [%s] ---------", (i + 1)));
			for (String key : tests.keySet()) {
				runWithMonitor(tests.get(key), runCount, key);
			}
		}
	}


	private static void runWithMonitor(Subject test, int runCount, String tag) {
		long start = System.currentTimeMillis();
		for (int i = 0; i < runCount; i++) {
			test.test(i);
		}
		long end = System.currentTimeMillis();
		System.out.println("[" + tag + "] Elapsed Time:" + (end - start) + "ms");
	}
}